package com.agileai.portal.controller.auth;

import com.agileai.domain.DataParam;
import com.agileai.hotweb.bizmoduler.core.TreeAndContentManage;
import com.agileai.hotweb.controller.core.TreeAndContentManageEditHandler;
import com.agileai.hotweb.domain.FormSelectFactory;
import com.agileai.hotweb.renders.AjaxRenderer;
import com.agileai.hotweb.renders.ViewRenderer;
import com.agileai.portal.bizmoduler.auth.SecurityGroupManage;
import com.agileai.portal.extend.uui.UserSyncHelper;
import com.agileai.portal.filter.UserCacheManager;
import com.agileai.portal.wsclient.uui.ResultStatus;
import com.agileai.portal.wsclient.uui.UserModel;
import com.agileai.portal.wsclient.uui.UserSync;
import com.agileai.util.CryptionUtil;

public class SecurityUserEditHandler
        extends TreeAndContentManageEditHandler {

    public SecurityUserEditHandler() {
        super();
        this.serviceId = buildServiceId(SecurityGroupManage.class);
        this.tabId = "SecurityUser";
        this.columnIdField = "GRP_ID";
        this.contentIdField = "USER_ID";
    }

    protected void processPageAttributes(DataParam param) {
        setAttribute("USER_SEX",
                     FormSelectFactory.create("USER_SEX")
                                      .addSelectedValue(getOperaAttributeValue("USER_SEX",
                                                                               "M")));
        setAttribute("USER_STATE",
                     FormSelectFactory.create("SYS_VALID_TYPE")
                                      .addSelectedValue(getOperaAttributeValue("USER_STATE",
                                                                               "1")));
    }

    protected SecurityGroupManage getService() {
        return (SecurityGroupManage) this.lookupService(this.getServiceId());
    }
    
	public ViewRenderer doSaveAction(DataParam param){
		String rspText = SUCCESS;
		TreeAndContentManage service = this.getService();
		String operateType = param.get(OperaType.KEY);
		if (OperaType.CREATE.equals(operateType)){
			String colIdField = service.getTabIdAndColFieldMapping().get(this.tabId);
			String columnId = param.get(this.columnIdField);
			param.put(colIdField,columnId);
			String userPassword = param.get("USER_PWD");
			
			boolean continueTag = true;
			if (UserSyncHelper.isEnableUserInfoSync()){
				continueTag = this.createRemoteUser(param);
			}
			if (continueTag){
				String encodePassword = CryptionUtil.md5Hex(userPassword);
				param.put("USER_PWD",encodePassword);
				getService().createtContentRecord(tabId,param);	
			}else{
				rspText = FAIL;
			}
		}
		else if (OperaType.UPDATE.equals(operateType)){
			boolean continueTag = true;
			if (UserSyncHelper.isEnableUserInfoSync()){
				continueTag = this.modifyRemoteUser(param);
			}
			if (continueTag){
				getService().updatetContentRecord(tabId,param);	
				String userCode = param.get("USER_CODE");
				UserCacheManager.getOnly().removeUser(userCode);
			}else{
				rspText = FAIL;
			}
		}
		return new AjaxRenderer(rspText);
	}
	
    private boolean createRemoteUser(DataParam param){
    	boolean result = false;
    	try {
    		UserSync userSync = UserSyncHelper.getUserSyncService();
    		String tokenId = UserSyncHelper.genTokenId("createUser");
    		UserModel userModel = new UserModel();
    		userModel.setId(param.get("USER_CODE"));
    		userModel.setMail(param.get("USER_MAIL"));
    		userModel.setPassword(param.get("USER_PWD"));
    		String userState = param.get("USER_STATE");
    		if ("1".equals(userState)){
    			userModel.setStatus("0");
    		}else{
    			userModel.setStatus("-1");    			
    		}
    		ResultStatus resultStatus = userSync.createUser(tokenId, userModel);
    		result = resultStatus.isSuccess();
		} catch (Exception e) {
			result = false;
			log.error(e.getLocalizedMessage(), e);
		}
    	return result;
    }	
    private boolean modifyRemoteUser(DataParam param){
    	boolean result = false;
    	try {
    		UserSync userSync = UserSyncHelper.getUserSyncService();
    		String tokenId = UserSyncHelper.genTokenId("modifyUser");
    		UserModel userModel = new UserModel();
    		userModel.setId(param.get("USER_CODE"));
    		userModel.setMail(param.get("USER_MAIL"));
    		String userState = param.get("USER_STATE");
    		if ("1".equals(userState)){
    			userModel.setStatus("0");
    		}else{
    			userModel.setStatus("-1");    			
    		}
    		ResultStatus resultStatus = userSync.modifyUser(tokenId, userModel);
    		result = resultStatus.isSuccess();
		} catch (Exception e) {
			result = false;
			log.error(e.getLocalizedMessage(), e);
		}
    	return result;
    }	    
}
